﻿using System;
using System.Linq;
#if ODIN_INSPECTOR
using Sirenix.OdinInspector;
#endif
using UnityEngine;
using UnityEngine.InputSystem;

namespace JH
{
    /// <summary>
    ///  折线图鼠标悬浮时，显示采样竖线，未悬浮时，不显示采样竖线的类
    /// </summary>
    public class LineActive : MonoBehaviour, IMouseHoverSample
    {
        /// <summary>
        ///  竖线
        /// </summary>
        [SerializeField]
#if ODIN_INSPECTOR
        [LabelText("竖线")]
#endif
        private RectTransform verticalLine;

        /// <summary>
        ///  父级RectTransform，用于计算竖线位置
        /// </summary>
        [SerializeField] private RectTransform parent;

        /// <summary>
        ///  渲染当前UI的相机
        /// </summary>
        [SerializeField] private Camera uiCamera;

        private void Awake()
        {
            // 确保竖线和交点在初始状态下不可见
            verticalLine.gameObject.SetActive(false);
        }

        /// <summary>
        ///  当鼠标悬浮状态改变时调用
        /// </summary>
        public void OnHoverStateChanged(bool newHoverState)
        {
            if (verticalLine) verticalLine.gameObject.SetActive(newHoverState);
        }

        /// <summary>
        ///  悬浮时，每帧采样数据调用
        /// </summary>
        public void OnSample(LineVertexInfo sample)
        {
            // 如果竖线和交点未设置，直接返回
            if (verticalLine == null) return;

            // 鼠标位置转换为父节点的本地位置
            Vector2 mousePosition = Mouse.current.position.ReadValue();
            if (parent != null &&
                RectTransformUtility.ScreenPointToLocalPointInRectangle(parent, mousePosition, uiCamera,
                    out Vector2 localPoint))
            {
                // 设置竖线位置
                verticalLine.anchoredPosition = new Vector2(localPoint.x, 0);
                return;
            }

            // 设置竖线位置，将UV坐标的x值映射到0~Width设置给AnchoredPosition.x即可
            var u = sample.UV.x;
            var width = u * sample.BoundaryHandler.Width;
            verticalLine.anchoredPosition = new Vector2(width, 0);
        }

        private void OnValidate()
        {
            var rectChildren = GetComponentsInChildren<RectTransform>(true);
            verticalLine = rectChildren.FirstOrDefault(i => i.name == "竖线");

            var rectTransform = verticalLine?.GetComponent<RectTransform>();
            if (rectTransform)
            {
                rectTransform.anchorMin = Vector2.zero;
                rectTransform.anchorMax = new Vector2(0, 1);
                rectTransform.pivot = new Vector2(0, 0f);
                rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, 0);
                rectTransform.anchoredPosition = new Vector2(0, 0);

                parent = rectTransform.parent as RectTransform;
            }

            var canvas = GetComponentInParent<Canvas>(true);
            if (canvas) uiCamera = canvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : canvas.worldCamera;
        }
    }
}